const pdfjs = require('pdfjs-dist/legacy/build/pdf');
const fs = require('fs');
const path = require('path');
const Canvas = require('canvas');

const file_path = path.resolve(__dirname, './1.pdf');
const CMAP_URL = '../node_modules/pdfjs-dist/cmaps/';

async function getPdfCanvas(file) {
  const readStream = fs.readFileSync(file_path);
  const data = new Uint8Array(readStream);

  let loadingTask = pdfjs.getDocument({
    data,
    cMapUrl: CMAP_URL,
    cMapPacked: true
  });
  try {
    let pdfdoc = await loadingTask.promise;

    const page = await pdfdoc.getPage(1);
    const viewport = page.getViewport({ scale: 1.0 });

    const canvas = Canvas.createCanvas(viewport.width, viewport.height);
    const context = canvas.getContext('2d');

    const renderContext = {
      canvasContext: context,
      viewport
    };

    const renderTask = page.render(renderContext);
    await renderTask.promise;
  } catch (error) {
    console.warn(error);
  }
}

module.exports = getPdfCanvas;
